﻿using Application.Permissions.Interfaces;
using Application.Permissions.Models;
using Infrastructure.Exceptions;

namespace Infrastructure.Services
{
    public class PermissionService : IPermissionService
    {
        private readonly IPermissionCache cache;

        public PermissionService(IPermissionCache cache)
        {
            this.cache = cache;
        }
        public IReadOnlyList<PermissionGroup> GetAll()
        {
            List<PermissionGroup> result = [];
            foreach (var item in cache.PermissionDict)
            {
                var dtos = item.Value.Select(x => new PermissionDto(x.PermissionName, x.PermissionSign, x.Description)).ToArray();
                result.Add(new(item.Key, dtos));
            }
            return result;
        }

        public PermissionDto GetBySign(string sign)
        {
            if(cache.SignDict.TryGetValue(sign,out var result))
            {
                return new(result.PermissionName, result.PermissionSign, result.Description);
            }
            throw new PermissionNotFoundException($"权限{sign}不存在");
        }

        public bool IsValidSign(string sign) => cache.SignDict.ContainsKey(sign);

        public async Task ReloadAsync()
        {
            await cache.ReloadAsync();
        }

        /// <summary>
        /// 同步加载权限列表 用于初始化构造
        /// </summary>
        public void Reload()
        {
            cache.Reload();
        }
    }
}
